package com.fatsatsuma.email;

import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.mail.EmailException;
import org.apache.log4j.Logger;

/**
 * @author $Id: EmailService.java,v 1.3 2006/12/15 15:55:55 gevans Exp $
 */
public class EmailService implements IEmailService {

	private Logger log = Logger.getLogger(this.getClass());

	public IEmailTemplate getEmailTemplateByKey(String key) {
		throw new NotImplementedException();
	}

	public EmailTemplate getEmailTemplateFromUrl(String url) throws WebRequestFailedException {
		EmailTemplate emailTemplate = new EmailTemplate();
		emailTemplate.setContentType("text/html");
		emailTemplate.setBodyHtml(HtmlUtils.getPageAsString(url));
		emailTemplate.setBodyText("If you have problems viewing this email please view : " + url);
		return emailTemplate;
	}

	public void sendEmail(IEmailTemplate emailTemplate, IReceipent receipent, String host)
			throws EmailException {
		try {
			ITemplateHandler handler = new VelocityTemplateHandler();
			handler.setTemplate(emailTemplate);

			IContext context = handler.getContext();
			// add the user to the properties
			if (receipent != null) {
				context.setParameter("user", receipent);
			}

			// get the message and send it
			IEmail mail = handler.generateEmail(context);

			// set the host value
			mail.setHostName(host);

			// send the message
			mail.send();

		} catch (Exception exp) {
			log.error("Mail sending failed: " + exp.toString());
			throw new EmailException("Unable to send message", exp);
		}
	}
}
